<script lang="ts" setup>
import ContractForm from './contract-form.vue'
import { useUserStore } from '@fl/store/modules/user'
import { useAddContract, useGetContractInfo } from '@fl/api/mall-api'
import { ElLoading } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { useGetAuthUrl } from '@fl/api/supplier'

const { meta: { isAdmin } } = useRoute()

const authUrlParams = computed(() => ({
    redirectUrl: location.href,
    flag: !isAdmin,
}))

const { data: authUrlData } = useGetAuthUrl(authUrlParams)

const { mutate: addMutate } = useAddContract()

const contractForm = ref<InstanceType<typeof ContractForm> | null>(null)

const { back } = useRouter()

const userStore = useUserStore()

const userInfo = computed(() => userStore.getUserInfo)

const isSupplier = computed(() => userInfo.value?.sysUser?.roles?.[0]?.roleKey === 'supplier')

const id = ref('')
const { data } = useGetContractInfo(id)

const initialData = ref({
    isAssociated: '否',
    partyA: userInfo.value?.enterpriseName,
    partyAId: userInfo.value?.enterpriseId,
    priceType: 1,
    contractPrice: 0,
    agreementCode: '', // 协议编码
    agreementName: '', // 协议名称
    agreementType: '', // 协议类型：1 为私有协议，2 为总价合同
    contractFileList: [], // 合同文件列表
    endDate: '', //	协议有效期结束日期
    otherFileList: [], // 合同附件列表
    partyB: '', // 乙方
    partyBId: '', // 乙方id
    productList: [], // 商品列表
    relationAgreementId: '', // 关联的协议id
    relationAgreementName: '', // 关联的协议名称
    startDate: '', // 协议有效期起始日期
    status: 0,
    initiationTime: [], // 有效期
    flag: 1,
})

function handleAction(val: any, status: number, onSuccess?: (res: any) => void) {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    addMutate(
        { ...val, status },
        {
            onSuccess: (res) => {
                if (Number(res) === 1) {
                    ElMessageBox.confirm('未授权电子签章', '提示', {
                        confirmButtonText: '去授权',
                        cancelButtonText: '取消',
                        type: 'warning',

                    }).then(() => {
                        if (!unref(authUrlData)?.authUrl) {
                            return
                        }
                        window.open(unref(authUrlData)?.authUrl, '_self')
                    })
                    return
                }
                ElMessage.success('操作成功')
                onSuccess?.(res) // 这里传递 res
            },
            onSettled: () => {
                loading.close()
            },
        },
    )
}
function handleSign(val: any) {
    handleAction(val, 0, (res) => { // 这里接收 res
        id.value = res
        contractForm.value!.changeIsFirst()
    })
}
function handleSave(val: any) {
    handleAction(val, 0, back)
}

function handleSubmit(val: any) {
    handleAction(val, 2, back)
}

watchEffect(() => {
    if (data.value) {
        console.log(data.value, 'watchEffect')
        initialData.value = cloneDeep(data.value)
    }
})
</script>

<template>
    <ContractForm ref="contractForm"
                  :is-supplier="isSupplier"
                  :initial-data="initialData"
                  @save="handleSave"
                  @submit="handleSubmit"
                  @sign="handleSign"
    />
</template>
